# coding: utf-8

from tea.models import *
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse

def NewBasket(request):
    NewBasket=Basket(call=False, end=False)
    NewBasket.save()
    request.session['basket_pk']=NewBasket.pk

def ViewsMain(request):
    DataGood=Good.objects.all().order_by('-number')[:10]
    DataType=Type.objects.all()
    return render_to_response('view_main.html', {'DataGood': DataGood, 'DataType': DataType, })
    
def ViewsGood(request, pk):
    DataGood=Good.objects.get(pk=pk)
    form=GoodAddForm()
    DataType=Type.objects.all()
    return render_to_response('views_good.html', {'DataGood': DataGood, 'DataType': DataType,'form':form }) 
    
def ViewsType(request, pk):
    DataGood=Good.objects.filter(type=pk)
    DataType=Type.objects.all()
    return render_to_response('view_main.html', {'DataGood': DataGood, 'DataType': DataType, })

def ViewsBasket(request):
    if not request.session.get('basket_pk'):
        NewBasket(request)
    DataBasket=Basket.objects.get(pk=request.session.get('basket_pk'))
    if request.method=='POST':
        form=BasketForm(request.POST, instance=DataBasket)
        if form.is_valid():
            form.save()
            DataBasket.end=True
            DataBasket.save()
            del request.session['basket_pk']
            return HttpResponseRedirect(reverse('tea.views.ViewsMain'))
    else:
        form=BasketForm()
        DataGoodBasket=DataBasket.goodbasket_set.all()
        DataType=Type.objects.all()
        return render_to_response('views_basket.html', {'DataBasket': DataBasket, 'DataType': DataType,'DataGoodBasket':DataGoodBasket, 'form':form,  })
    
def AddGood(request):
    if bool(request.POST['preorder']):
        preorder=True
        number_ord=0
    else:
        preorder=False
        number_ord=eval(request.POST['number'])
    if not request.session.get('basket_pk'):
        NewBasket(request)
    try: 
        GoodInBasket=GoodBasket.objects.get(good=eval(request.POST['good']),  basket=request.session.get('basket_pk'))
        GoodInBasket.number+=number_ord
        GoodInBasket.save()
    except:
        GoodInBasket=GoodBasket(good_id=eval(request.POST['good']), number=number_ord,  preorder=preorder, basket_id=request.session.get('basket_pk'))
        GoodInBasket.save()
    return HttpResponseRedirect(reverse('tea.views.ViewsBasket'))

def DelGood(request):
    GoodInBasket=GoodBasket.objects.get(pk=eval(request.POST['good']))
    GoodInBasket.delete()
    return HttpResponseRedirect(reverse('tea.views.ViewsBasket'))

def PreOrder(request):
    pass
    
